package com.example.mcpweather.tool;

import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;
@Service
@Slf4j
public class ToDayInHistorySearch {

    private static final String CLIENT_ID = "d491fe96-f9e5-4ebe-bd90-a63dd795b399";
    private static final String CLIENT_SECRET = "dd068ea73be2f1b67d1ec1d2e684e0192d30c3b427f93bd82d02ea4f83ec534e";
    @Tool(name = "getTodayInHistorySearch", description = "查询历史上的今天")
    public String getTodayInHistory(@ToolParam(description = "日期", required = true) String date) {
        try {
            String url = "https://www.idcd.com/api/today-in-history?date="+date;
            log.info("查询历史上的今天url = {}", url);
            log.info("查询历史上的今天date = {}", date);
            // 生成请求参数
            String nonce = UUID.randomUUID().toString().replace("-", "");
            String timestamp = String.valueOf(Instant.now().getEpochSecond());
            String signatureMethod = "HmacSHA256";
            // 生成签名
            String signature = generateSignature(nonce, timestamp);
            // 发送带认证头的请求
            String response = HttpRequest.get(url)
                    .header("ClientID", CLIENT_ID)
                    .header("Nonce", nonce)
                    .header("Timestamp", timestamp)
                    .header("Signature", signature)
                    .header("SignatureMethod", signatureMethod)
                    .execute()
                    .body();
            return response;
        } catch (Exception e) {
            log.error("查询历史上的今天失败", e);
            return "查询失败: " + e.getMessage();
        }
    }

    /**
     * 生成API签名
     * @param nonce 随机字符串
     * @param timestamp 时间戳
     * @return 签名字符串
     */
    private String generateSignature(String nonce, String timestamp) {
        // 根据示例说明，签名方法固定为 HmacSHA256
        String signatureMethod = "HmacSHA256";

        // 按照指定顺序拼接待签名字符串: clientID + nonce + timestamp + signatureMethod
        String plainText = CLIENT_ID + nonce + timestamp + signatureMethod;
        log.debug("待签名字符串: {}", plainText);

        // 使用HmacSHA256算法生成签名
        HMac mac = new HMac(HmacAlgorithm.HmacSHA256, CLIENT_SECRET.getBytes());
        byte[] signData = mac.digest(plainText);

        // 转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : signData) {
            sb.append(String.format("%02x", b));
        }

        String signature = sb.toString();
        log.debug("生成的签名: {}", signature);

        return signature;
    }
}
